import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class DaysSelectionSlider extends StatefulWidget {
  /// The number of days currently selected.
  // final double numberOfDays;
  final RangeValues selectedRange;

  /// A callback listening for value changes.
  //final ValueChanged<double> onChanged;
  final ValueChanged<RangeValues> onChanged;

  /// Display a slider that allows to define how many days to go back
  /// (range 1 to 7).
  const DaysSelectionSlider({
    super.key,
    //required this.numberOfDays,
    required this.selectedRange,
    required this.onChanged,
  });

  @override
  State<StatefulWidget> createState() {
    return _DaysSelectionSliderState();
  }
}

class _DaysSelectionSliderState extends State<DaysSelectionSlider> {
  String get sevenDaysAgoDate {
    final date = DateTime.now().subtract(const Duration(days: 6));
    return DateFormat('MM-dd').format(date);
  }
  String _dayLabel(double daysAgo) {
    final date = DateTime.now().subtract(Duration(days: daysAgo.round() - 1));
    return DateFormat('MM-dd').format(date);
  }

  @override
  Widget build(BuildContext context) {
    RangeValues sliderValues = RangeValues(
      8 - widget.selectedRange.end,
      8 - widget.selectedRange.start,
    );

    return Padding(
      padding: const EdgeInsets.all(12.0),
      child: Column(
        children: [
          const Center(
            child: Text(
              '显示哪几天的轨迹？',
              style: TextStyle(fontSize: 20),
            ),
          ),
          Row(
            children: [
              //const Text('1', style: TextStyle(fontWeight: FontWeight.bold)),
              Text(
                sevenDaysAgoDate,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              Expanded(

                child: RangeSlider(
                  // value: widget.numberOfDays,
                  values: sliderValues,
                  min: 1,
                  max: 7,
                  //label: '${widget.numberOfDays.round()}',
                  labels: RangeLabels(
                    _dayLabel(8 - sliderValues.start),
                    _dayLabel(8 - sliderValues.end),
                  ),
                  divisions: 6,
                  // onChanged: widget.onChanged,
                  onChanged: (RangeValues values) {
                    // 将滑块值转换回外部范围 (反转回来)
                    final newRange = RangeValues(
                      8 - values.end,
                      8 - values.start,
                    );

                    // 触发回调
                    widget.onChanged(newRange);
                  },
                ),
              ),
              //const Text('7', style: TextStyle(fontWeight: FontWeight.bold)),
              const Text(
                '今天',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
